Skip to main content

Stack

A stack has only one entry/exit point.

LIFO: Last in First Out. It implies that the element that is inserted last, comes out first.

Stack is used for managing order of processes

Operations

Push: add an element to the stack
Pop: remove an element from the stack
Peek: display the topmost element of the stack

Errors

  1. Stack overflow: When user tries to add an element to a already full stack.
  2. Stack underflow: When user tries to remove an element from an empty stack.

Code

#include <stdio.h>

// FUNCTION PROTOTYPES
void push(int *ptr);
void pop(int *ptr);
void display(int *ptr);
int peek(int *ptr);

// GLOBAL VARIABLES
int top = -1;
int N;

int main()
{
printf("Enter N : \n");
scanf("%d", &N);
int ar[N];

// ACCEPTING N ELEMENTS OF STACK
for (int i = 0; i < N; i++)
{
push(ar);
}

display(ar);
pop(ar);
pop(ar);
display(ar);
push(ar);
display(ar);

int topmost = peek(ar);
printf("\nTopmost element: %d", topmost);
printf("\n");

return 0;
}

// INPUT STACK ELEMENTS
void push(int *ptr)
{
// STACK OVERFLOW
if (top == N - 1)
{
printf("\nStack Overflow");
}
else
{
top++;
printf("\nEnter Element Stack[%d]: ", top + 1);
scanf("%d", &*(ptr + top));
// *(ptr + top) = x;
}
}

// REMOVE STACK ELEMENT
void pop(int *ptr)
{
// STACK UNDERFLOW
if (top == -1)
{
printf("\nNo Element to POP");
}
else
{
printf("\nRemoved Element: %d", *(ptr + top));
top--;
}
}

// DISPLAY THE STACK
void display(int *ptr)
{
printf("\nElements in Stack:\n");
for (int i = 0; i <= top; i++)
{
printf(" %d", *(ptr + i));
}
}

// PEEK: DISPLAY TOPMOST ELEMENT
int peek(int *ptr)
{
// STACK UNDERFLOW
if (top == -1)
{
printf("\nNo Element to PEEK");
}
else
{
return *(ptr + top);
}
}

Find a visual representation of solution of Stack here